<template>
  <div>
    <bread-crumb
      class="bread-crumb-padding"
      :list="breadCrumb"
      :user="true"
    ></bread-crumb>
    <div class="user-main-box">
      <user-tab-list :list="tablist"></user-tab-list>
      <div style="position: relative">
        <div class="filter-line b-b-d flx-row-s-c">
          <span class="item-name">竞价状态</span>
          <span
            v-for="(item, index) in biddingStatus"
            :key="index"
            class="select-item"
            :class="[index == biddingStatusSelect ? 'active' : 'normal']"
            style="margin-right: 20px"
            @click="changeClassify(index)"
          >
            {{ item }}
          </span>
        </div>
        <div class="filter-line b-b-d flx-row-s-c">
          <span class="item-name">出价状态</span>
          <span
            v-for="(item, index) in bidStatus"
            :key="'s' + index"
            class="select-item"
            :class="[index == bidStatusSelect ? 'active' : 'normal']"
            style="margin-right: 20px"
            @click="bidStatusSelectChange(index)"
          >
            {{ item.name }}
          </span>
        </div>
        <div class="filter-line b-b-d flx-row-s-c">
          <template v-if="biddingStatusSelect == 0">
            <span class="item-name">结拍时间</span>
            <span
              v-for="(item, index) in rushTimeList"
              :key="'e' + index"
              class="select-item"
              :class="[
                rushTime == index ? 'active' : 'normal',
                index < rushTimeList.length - 1 ? 'mg-r-25' : '',
              ]"
              @click="rushTimeChange(index)"
              >{{ item.name }}</span
            >
          </template>
          <template v-if="biddingStatusSelect == 1">
            <span class="item-name">结拍时间</span>
            <Select @on-change="changeDateType" v-model="dateType" style="width: 150px; margin-right: 10px">
              <Option
                  v-for="item in dateTypeList"
                  :value="item.type"
                  :key="item.type"
              >{{ item.name }}</Option
              >
            </Select>
            <DatePicker
              :editable="false"
              type="daterange"
              split-panels
              placeholder="请选择"
              style="width: 300px"
              @on-change="dateChange"
              :options="dateOption"
              :value="time"
            ></DatePicker>
          </template>
          <span class="item-name">当前价格</span>
          <InputNumber
            v-model.trim="startPrice"
            number
            placeholder="请输入"
            maxlength="10"
            type="number"
            :min="0"
            style="width: 120px"
          />
          <div class="two-input-middle"></div>
          <InputNumber
            v-model.trim="endPrice"
            number
            placeholder=""
            type="number"
            maxlength="10"
            :min="0"
            style="width: 120px"
          />
        </div>
        <div class="filter-line b-b-d flx-row-s-c">
          <span class="item-name" style="text-align: right">域名</span>
          <div class="wrapdmTextarea">
            <div class="textarea-warp" style="z-index: 200; top: 0;">
              <Input class="ui-input dmTextarea" :class="dmName ? 'dmTyping' : ''" @on-focus="dmName = true"
                     @on-blur="dmName = false" v-model.trim="domainName" type="textarea" placeholder="批量请换行分隔">
                <template #suffix>
                  <Icon type="ios-search"/>
                </template>
              </Input>
            </div>
          </div>
          <span class="item-name">长度</span>
          <InputNumber
            v-model.trim="startLen"
            number
            placeholder="请输入"
            maxlength="10"
            type="number"
            :min="0"
            style="width: 120px"
          />
          <div class="two-input-middle"></div>
          <InputNumber
            v-model.trim="endLen"
            number
            placeholder=""
            type="number"
            maxlength="10"
            :min="0"
            style="width: 120px"
          />
          <span class="item-name">竞价类型</span>
          <Select v-model="biddingType" multiple  style="width: 150px">
            <Option
              v-for="(item) in biddingTypeList"
              :value="item.value"
              :key="item.value"
              >{{ item.name }}</Option
            >
          </Select>
          <div
              class="user-strong-button line-button-size"
              style="margin: 0px 10px 0px 30px;"
              @click="pageChange(1)"
          >
            搜索
          </div>
          <div class="user-normal-button line-button-size" @click="reset">
            重置
          </div>
        </div>
      </div>
    </div>

    <div class="user-main-box pub-m-t-20">
      <div style="position: relative">
        <Spin :withIcon="true" v-if="loading"></Spin>
        <div class="filter-line search-result-line flx-row-bw-c">
          <span class="c-g f-14"
            >搜索结果共<span class="c-black">{{
              total != null ? ` ${total} ` : ""
            }}</span
            >条</span
          >
          <div
            class="pub-m-l-40"
            v-if="biddingStatusSelect == 0"
            style="float: right; display: inline-flex; align-items: center"
          >
            <Checkbox v-model="isAutoRefresh" @on-change="autoRefresh">
              <span v-if="isAutoRefresh"
                >自动刷新(<span style="color: red"
                  >{{ count > 9 ? count : "0" + count }}s</span
                >)</span
              >
              <span v-else>自动刷新</span>
            </Checkbox>
            <Input
              class="bidding-input"
              type="text"
              @on-keyup="
                batchPrice = batchPrice.replace(
                  /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                  '$1'
                )
              "
              @on-change="changAllPrice()"
              style="width: 180px"
              v-model="batchPrice"
              enter-button="出价"
            >
              <span slot="append">
                <Button
                  @click.prevent="bidV2()"
                  class="user-strong-button line-button-size"
                  style="height: 32px"
                >
                  批量出价
                </Button>
              </span>
            </Input>
          </div>
        </div>
        <div class="my-domain-table">
          <Table
            :loading="loading"
            :columns="listColumns"
            :data="list"
            :disabled-hover="true"
            @on-selection-change="selectionChange"
          >
            <template slot="action" slot-scope="{ row }">
              <div class="flx-row-c-c" style="justify-content: left;">
                <Input
                  class="bidding-input"
                  type="text"
                  @on-keyup="
                    row.nextPrice = row.nextPrice.replace(
                      /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                      '$1'
                    )
                  "
                  @on-focus="focusPrice(row.biddingId, row.nextPrice)"
                  @on-blur="blurPrice(row.biddingId)"
                  @on-change="changPrice(row)"
                  style="width: 180px"
                  v-model="row.nextPrice"
                  v-if="biddingStatusSelect == 0"
                  enter-button="出价"
                >
                  <span slot="append">
                    <Button
                      @click.prevent="bid(row)"
                      class="user-strong-button line-button-size"
                      style="height: 32px; width: 60px"
                    >
                      出价
                    </Button>
                  </span>
                </Input>
                <div
                  class="user-strong-button form-button-size"
                  style="width: 60px"
                  v-else
                  @click="toDetail(row.biddingId)"
                >
                  详情
                </div>
              </div>
            </template>
          </Table>
        </div>

        <div class="form-page-bottom-area flx-row-c-c">
          <Page
            :total="total"
            :current="page"
            :page-size="pageSize"
            :page-size-opts="pageSizeOpts"
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
            show-total
          />
        </div>
      </div>
    </div>
    <Modal
      v-model="batchBidModel"
      title="批量出价"
      width="600"
      @on-visible-change="modelChange"
      :mask-closable="false"
    >
      <div style="padding: 10px">
        <Table
          :key="Math.random()"
          height="400"
          :columns="columns"
          :data="bidData"
        >
          <template #msg="{ row }">
            <span style="color: #ed4014" v-if="row.status === 0">{{
              row.msg
            }}</span>
            <span style="color: #19be6b" v-if="row.status === 1">出价成功</span>
          </template>
        </Table>
      </div>
      <!--解决弹框自动关闭-->
      <div slot="footer">
        <Button type="text" @click="batchBidModel = false">取消</Button>
        <Button
          type="primary"
          class="user-strong-button"
          :loading="modelLoading"
          @click="batchOk"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import { getMyBidding, bidBatch} from "@/api/user";
import { createDateTypeList } from "@/utils/publicData";
export default {
  name: "VipMybiddings",
  data() {
    return {
      dmName: false,
      loading: false,
      modelLoading: false,
      breadCrumb: [{name: "管理中心"},{ name: "域名竞价" }, { name: "我的竞价" }],
      tablist: [
        {
          name: "我的竞价",
          to: "/user/mybiddings",
        },
      ],
      biddingStatus: ["竞价中", "竞价结束"],
      biddingStatusSelect: 0,
      biddingType:[],
      biddingTypeList:[],
      bidStatus: [
        {
          name: "全部",
          value: "",
        },
        {
          name: "领先",
          value: 0,
        },
        {
          name: "落后",
          value: 1,
        },
      ],
      bidStatusSelect: 0,
      rushTimeList: [],
      rushTime: 0,

      // 表单数据
      time: [],
      startTime: "",
      endTime: "",
      startLen: null,
      endLen: null,
      startPrice: null,
      endPrice: null,
      domainName: "",

      // 分页设置
      total: null,
      pageSizeOpts: [50, 100, 200],
      pageSize: 50,
      page: 1,
      list: [],
      isAutoRefresh: false,
      autoInterval: null,
      countInterval: null,
      inputList: {},
      focusBidding: {},
      selectAllEnable: false,
      selectList: [],
      batchBidModel: false,
      columns: [
        {
          title: "域名",
          key: "domainName",
        },
        {
          title: "出价价格",
          key: "nextPrice",
        },
        {
          title: "出价提示",
          key: "msg",
          slot: "msg",
        },
      ],
      bidData: [],
      count: 20,
      batchPrice: null,
      listColumns: [],
      columnsCopy: [
        {
          width: 50,
          type: "selection",
          align: "center",
        },
        {
          width: 50,
          title: "序号",
          type: "index",
          align: "center",
        },
        {
          minWidth: 100,
          title: "域名",
          align: "left",
          key: "domainName",
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: "#1c9cdf",
                  cursor: "pointer",
                },
                on: {
                  click: () => {
                    this.toDetail(params.row.biddingId);
                  },
                },
              },
              params.row.domainName
            );
          },
        },
        {
          minWidth: 80,
          align: "left",
          key: "currentPrice",
          renderHeader: (h) => {
            return h(
              "span",
              this.biddingStatusSelect == 0 ? "当前价格" : "结拍价格"
            );
          },
          render: (h, params) => {
            return h("span", "￥" + params.row.currentPrice);
          },
        },
        {
          minWidth: 100,
          title: "您的出价",
          align: "left",
          key: "price",
          render: (h, params) => {
            return h("span", [
              h(
                "span",
                {
                  style: {
                    marginRight: "10px",
                  },
                },
                "￥" + params.row.price
              ),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                params.row.biddingStatus == 0 ? "领先" : ""
              ),
              h("span", params.row.biddingStatus == 1 ? "落后" : ""),
            ]);
          },
        },
        {
          minWidth: 100,
          title: "您的代理价",
          align: "left",
          key: "agentPrice",
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: "red",
                },
              },
              "￥" + params.row.agentPrice
            );
          },
        },
        {
          minWidth: 80,
          align: "left",
          key: "bond",
          renderHeader: (h) => {
            return h("span", this.biddingStatusSelect == 0 ? "保证金" : "");
          },
        },

        {
          minWidth: 80,
          align: "left",
          key: "",
          renderHeader: (h) => {
            return h(
              "span",
              this.biddingStatusSelect == 0 ? "剩余时间" : "结拍时间"
            );
          },
          render: (h, params) => {
            return h(
              "span",
              this.biddingStatusSelect == 0
                ? params.row.remainingTime
                : params.row.endTime
            );
          },
        },
        {
          minWidth: 180,
          title: "操作",
          align: "left",
          slot: "action",
        },
      ],
      dateType: 0,
      dateTypeList: [],
      dateOption: {
      },
    };
  },
  created() {
    this.createDateTypeList()
    this.getRushTimeList();
    this.getMyBidding();
    if (this.biddingStatusSelect == 0) {
      this.listColumns = this.columnsCopy;
    } else {
      this.listColumns = this.columnsCopy.filter((col) => col.ley == "bond");
    }
  },
  async mounted(){
     const data = await this.$storage.getDomainQueryTerm();
     this.biddingTypeList = data.platforms;
  },
  methods: {
    changeDateType() {
      this.changeDateOption()
    },
    changeDateOption() {
      this.time = []
      this.startTime = null
      this.endTime = null
      this.dateOption = {
        disabledDate: date => {
          let item = this.dateTypeList.filter(item => item.type === this.dateType);
          return date && (date.valueOf() < item[0].startTime || date.valueOf() > item[0].endTime);
        }
      };
    },
    createDateTypeList() {
      this.dateTypeList = createDateTypeList(6)
      this.changeDateOption()
    },
    selectionChange(selection) {
      let arr = [];
      selection.forEach((item) => {
        arr.push(item.biddingId);
      });
      this.selectList = arr;
    },
    modelChange(val) {
      if (!val) {
        this.bidData = [];
        this.batchPrice = null;
      }
    },
    initData() {
      this.inputList = {};
      this.focusBidding = {};
      this.selectAllEnable = false;
      this.selectList = [];
    },
    selectAll() {
      if (this.selectAllEnable) {
        let arr = [];
        this.list.forEach((item) => {
          item.select = true;
          arr.push(item.biddingId);
        });
        this.selectList = arr;
      } else {
        this.list.forEach((item) => {
          item.select = false;
        });
        this.selectList = [];
      }
    },
    selectOne(item) {
      if (item.select) {
        this.selectList.push(item.biddingId);
      } else {
        this.selectList.splice(
          this.selectList.findIndex((one) => one === item.biddingId),
          1
        );
      }
    },
    focusPrice(biddingId, nextPrice) {
      this.focusBidding[biddingId] = nextPrice;
    },
    blurPrice(biddingId) {
      delete this.focusBidding[biddingId];
    },
    changPrice(item) {
      this.inputList[item.biddingId] = item.nextPrice;
      this.focusBidding[item.biddingId] = item.nextPrice;
      if (this.batchBidModel) {
        let filter = this.list.filter(
          (one) => one.biddingId === item.biddingId
        );
        filter[0].nextPrice = item.nextPrice;
      }
    },
    changAllPrice() {
      this.bidData.forEach((item) => {
        item.nextPrice = this.batchPrice;
      });
    },
    batchOk() {
      let list = this.bidData.map((item) => {
        return {
          biddingId: item.biddingId,
          price: item.nextPrice,
        };
      });
      this.bidBatch(list, 1);
    },
    // 出价
    bid(item) {
      this.$Modal.confirm({
        title: "提示",
        content: `是否确定出价${item.nextPrice}元？`,
        okText: "确定",
        cancelText: "取消",
        loading: true,
        onOk: () => {
          this.bidBatch(
            [
              {
                biddingId: item.biddingId,
                price: item.nextPrice,
              },
            ],
            0
          );
        },
      });
    },
    bidV2() {
      let arr = [];
      this.selectList.forEach((item) => {
        this.list
          .filter((one) => one.biddingId === item)
          .forEach((one) => {
            arr.push({
              biddingId: one.biddingId,
              domainName: one.domainName,
              nextPrice:
                this.batchPrice === null ? one.nextPrice : this.batchPrice,
            });
          });
      });
      this.bidData = arr;
      if (this.bidData.length === 0) {
        return this.$Message.warning("请选择出价域名");
      }
      if (this.batchPrice != null && this.batchPrice <= 0) {
        return this.$Message.warning("批量出价价格必须大于0");
      }
      this.batchBidModel = true;
    },
    async bidBatch(bidList, type) {
      if (bidList.length > 0) {
        this.modelLoading = true;
        let { result, data, message } = await bidBatch(bidList);
        this.modelLoading = false;
        if (result) {
          if (type === 0) {
            this.$Modal.remove();
            this.$Message.success(data[0].msg);
          } else {
            this.bidData.forEach((item) => {
              let filter = data.filter(
                (one) => item.biddingId === one.biddingId
              );
              if (filter.length > 0) {
                item.status = filter[0].status;
                item.msg = filter[0].msg;
              }
            });
          }
          this.getMyBidding();
        } else {
          this.$Message.warning(message);
        }
      }
    },
    autoRefresh() {
      if (this.autoInterval) {
        this.count = 20;
        clearInterval(this.autoInterval);
      }
      if (this.countInterval) {
        clearInterval(this.countInterval);
      }
      if (this.biddingStatusSelect === 0) {
        if (this.isAutoRefresh) {
          this.countInterval = setInterval(() => {
            this.count--;
            if (this.count === 0) {
              this.count = 20;
            }
          }, 1000);
          this.autoInterval = setInterval(() => {
            this.getMyBidding();
          }, 20000);
        }
      }
    },
    // 切换分类
    changeClassify(index) {
      if (index == this.biddingStatusSelect) return;
      this.biddingStatusSelect = index;
      if (this.biddingStatusSelect == 0) {
        this.listColumns = this.columnsCopy;
      } else {
        this.listColumns = this.columnsCopy.filter((col) => col.key !== "bond");
      }
      this.reset();
    },
    // 出价状态改变
    bidStatusSelectChange(index) {
      this.bidStatusSelect = index;
      this.pageChange(1);
    },
    // 结拍时间改变
    rushTimeChange(index) {
      this.rushTime = index;
      this.pageChange(1);
    },
    // 获取列表
    async getMyBidding() {
      if (this.startPrice || this.endPrice) {
        if (
          !(
            this.startPrice &&
            this.endPrice &&
            this.startPrice > 0 &&
            this.endPrice > 0 &&
            this.startPrice < this.endPrice
          )
        ) {
          this.$Message.warning("请确认筛选条件是否输入错误！");
          return;
        }
      }
      if (this.startLen || this.endLen) {
        if (
          !(
            this.startLen &&
            this.endLen &&
            this.startLen > 0 &&
            this.endLen > 0 &&
            this.startLen < this.endLen
          )
        ) {
          this.$Message.warning("请确认筛选条件是否输入错误！");
          return;
        }
      }
      this.loading = true;
      let domainName = this.domainName.replace(/\n/g, ",");
      let data = {
        biddingStatus: this.bidStatus[this.bidStatusSelect].value,
        status: this.biddingStatusSelect,
        domainName: domainName,
        limit: this.pageSize,
        page: this.page,
        startLen: this.startLen,
        endLen: this.endLen,
        startPrice: this.startPrice,
        endPrice: this.endPrice,
        platforms:this.biddingType,
        dateType:this.dateType,
      };
      if (this.biddingStatusSelect == 0) {
        if (this.rushTime != 0) {
          data.startTime = this.rushTimeList[this.rushTime].value;
          data.endTime = this.rushTimeList[this.rushTime].value;
        }
      } else {
        data.startTime = this.startTime;
        data.endTime = this.endTime;
      }
      let res = await getMyBidding(data);
      if (res.code == 200) {
        if (data.status === 0) {
          res.data.list.forEach((item) => {
            let filter = this.selectList.filter(
              (one) => one === item.biddingId
            );
            if (filter.length > 0) {
              item.select = true;
            }
            let element = this.focusBidding[item.biddingId];
            if (element != null) {
              if (item.nextPrice < element) {
                item.nextPrice = element;
              } else {
                delete this.focusBidding[item.biddingId];
              }
            } else {
              let filter = this.inputList[item.biddingId];
              if (filter != null) {
                if (item.nextPrice < filter) {
                  item.nextPrice = filter;
                } else {
                  delete this.inputList[item.biddingId];
                }
              }
            }
          });
          this.list = res.data.list;
          this.total = res.data.total;
        } else {
          this.list = res.data.list;
          this.total = res.data.total;
        }
      }
      this.loading = false;
    },
    // 日期选择改变
    dateChange(date) {
      this.startTime = date[0];
      this.endTime = date[1];
    },
    // 获取待抢注时间
    getRushTimeList() {
      let day1 = new Date();
      day1.setTime(day1.getTime() + 24 * 60 * 60 * 1000 * 2);
      let value1 =
        day1.getFullYear() +
        "-" +
        (day1.getMonth() + 1 > 9
          ? day1.getMonth() + 1
          : "0" + (day1.getMonth() + 1)) +
        "-" +
        (day1.getDate() > 9 ? day1.getDate() : "0" + day1.getDate());
      let day2 = new Date();
      day2.setTime(day2.getTime() + 24 * 60 * 60 * 1000);
      let value2 =
        day2.getFullYear() +
        "-" +
        (day2.getMonth() + 1 > 9
          ? day2.getMonth() + 1
          : "0" + (day2.getMonth() + 1)) +
        "-" +
        (day2.getDate() > 9 ? day2.getDate() : "0" + day2.getDate());
      let day3 = new Date();
      day3.setTime(day3.getTime());
      let value3 =
        day3.getFullYear() +
        "-" +
        (day3.getMonth() + 1 > 9
          ? day3.getMonth() + 1
          : "0" + (day3.getMonth() + 1)) +
        "-" +
        (day3.getDate() > 9 ? day3.getDate() : "0" + day3.getDate());
      this.rushTimeList = [
        {
          name: "全部",
          value: "",
        },
        {
          name: `${day3.getMonth() + 1}月${day3.getDate()}日`,
          value: value3,
        },
        {
          name: `${day2.getMonth() + 1}月${day2.getDate()}日`,
          value: value2,
        },
        {
          name: `${day1.getMonth() + 1}月${day1.getDate()}日`,
          value: value1,
        },
      ];
    },
    // 重置
    reset() {
      if (this.biddingStatusSelect == 0) {
        this.rushTime = 0;
      } else {
        this.startTime = "";
        this.endTime = "";
      }
      this.time = [];
      this.dateType = 0
      /*this.domainName = "";
      this.startLen = null;
      this.endLen = null;
      this.startPrice = null;
      this.endPrice = null;*/
      this.page = 1;
      // this.biddingType=[];
      this.getMyBidding();
    },
    // 切换页码
    pageChange(page) {
      this.page = page;
      this.initData();
      this.getMyBidding();
    },
    // 切换pageSize
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.initData();
      this.pageChange(1);
    },
    // 跳转到详情
    toDetail(id) {
      window.open(`/bidding/details?id=${id}`);
    },
  },
};
</script>

<style lang="scss" scoped>
.mg-r-25 {
  margin-right: 25px;
}
/deep/ .ivu-input-wrapper {
  background: #fff;
}
::v-deep .ivu-select-multiple .ivu-select-selection{
  height: auto !important;
}
::v-deep .ivu-table:before {
  height: 0;
}
::v-deep .bidding-input {
  input {
    margin-left: 2px;
  }

  .ivu-input-search {
    transition: background-color 0.3s, color 0.3s;
    background-color: var(--mainColor, #F68A0C) !important;
    color: #fff;
    border-color: var(--mainColor, #F68A0C) !important;
  }
  .ivu-btn {
    transition: background-color 0.3s, color 0.3s;
    background-color: var(--mainColor, #F68A0C);
    color: #fff;
    border-bottom-left-radius: initial;
    border-top-left-radius: initial;
    min-width: 64px;
  }
  .ivu-btn:focus {
    box-shadow: none;
  }
  .ivu-checkbox-wrapper {
    margin: 0;
  }
  .ivu-checkbox {
    margin: 0;
  }
}
.form-page-bottom-area {
  border: none;
}
.my-domain-table /deep/ {
  width: 100%;
  .form-page-bottom-area {
    border: none;
  }
  .ivu-table-wrapper {
    .ivu-table-cell {
      color: #000;
      &:nth-child(1) {
        padding-left: 10px;
        padding-right: 10px;
      }
    }
    .ivu-table-header {
      box-sizing: border-box;
    }
    .ivu-table-row {
      box-sizing: border-box;
      &:hover {
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
        transform: scale(1.01);
      }
    }
  }
  .tab-btn:hover {
    color: $mainColor;
    border-color: $mainColor;
  }
  .tab-btn:focus {
    box-shadow: none;
  }
  .table-domainName {
    color: $mainColor;
  }
}
</style>
